/*
 * Problem: 迷宫的最短路径（The shortest path of a maze from entrance to exit）
 * Author: Yuanshun L
 * Created: 7-Dec-2021
 * Topic: BFS
 */
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>

using namespace std;

typedef pair<int,int> P;
const int inf = 10000000;
const int maxn = 100+2;
char maze[maxn][maxn];
int d[maxn][maxn];
int n,m;
int sx,sy,tx,ty;

int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,-1,1};

int solve(){
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            d[i][j] = inf;
        }
    }
    int x,y;
    queue<P> q;
    d[sx][sy] = 0;
    q.push(P(sx,sy));
    while(!q.empty()){
        P p = q.front(); q.pop();
        for(int dir=0;dir<4;dir++){
            x = p.first + dx[dir];
            y = p.second + dy[dir];
            if( maze[x][y] == '#' ||  d[x][y] != inf) continue;
            d[x][y] = d[p.first][p.second] + 1;
            q.push(P(x,y));
        }
    }
    return d[tx][ty];
}

int main(){
    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);

    cin >> n >> m;
    for(int i=0;i<m;i++){
        cin >> maze[i];
    }

    sx = tx = -1;
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(maze[i][j] == 'S'){
                sx = i; sy = j;
            }
            if(maze[i][j] == 'G'){
                tx = i; ty = j;
            }
            if(sx > -1 && tx > -1)
                break;
        }
    }

    cout << solve() << endl;

    return 0;
}
